package com.zhisheng.day10_tlias.aop;

import com.zhisheng.day10_tlias.entry.OperateLog;
import com.zhisheng.day10_tlias.service.OperateLogService;
import com.zhisheng.day10_tlias.utils.MyThreadLocaUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/*
    专门针对 部门和员工的增删改操作记录日志的AOP
 */
@Component
@Aspect
public class MyOperateLogAop {

    @Autowired
    private OperateLogService operateLogService;

    @Around("@annotation(com.zhisheng.day10_tlias.anno.MyOperateLogBJ)")
    public Object writeLog(ProceedingJoinPoint pjp){
        // 创建 log对象,并调用  OperateLogService 业务层接口的记录日志的方法
        // 从ThreadLocal工具类中获取当前登陆人的id
        Integer id = MyThreadLocaUtils.get(Integer.class);
        String className = pjp.getSignature().getDeclaringTypeName();
        String name = pjp.getSignature().getName();
        Object[] args = pjp.getArgs();
        long cha = -1;
        Object proceed = null;
        try {
            long t1 = System.currentTimeMillis();
             proceed= pjp.proceed();
            long t2 = System.currentTimeMillis();
            cha = t2-t1;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }finally {
            String string = java.util.Arrays.toString(args);
            //创建 log对象,并调用  OperateLogService 业务层接口的记录日志的方法
            OperateLog log = new OperateLog(null,id, LocalDateTime.now(),className,name, string,proceed == null?"null":proceed.toString(),cha);
            operateLogService.insert(log);
        }
        return proceed;
    }

}
